/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package javaapplication1;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

/**
 *
 * @author new
 */
public class IncludeHandler {


    public int handleInclude(String sourceFile) throws FileNotFoundException, IOException{
        FileHandler fh = new FileHandler();
        BufferedReader br;
        BufferedWriter bw;
        ArrayList al = new ArrayList();
        String fileName = new String(sourceFile);
        String temp = "IncludeTemp";

        while(true){
            int i = 0;

            br = fh.openReadFile(fileName);
            String tempStr = br.readLine();

            BufferedWriter bwInclude = fh.openWriteFile(temp);

            while(tempStr != null){
                if(tempStr.contains("#INCLUDE")){
                    String includeFileName = tempStr.substring(tempStr.indexOf('<')+1,
                            tempStr.indexOf('>'));
                    if(al.contains(includeFileName)){
                        i++;
                        tempStr = br.readLine();
                        continue;
                    }
                    include(includeFileName, bwInclude);
                    i++;
                    al.add(includeFileName);
                }
                tempStr = br.readLine();
            }
            fh.closeWriteFile(bwInclude);
            if(i == 0){
                break;
            }
            fh.closeReadFile(br);
            delInclude(fileName, "DelIncludeTemp");
            System.gc();
            fh.compose(temp, fileName);
            System.gc();
            fh.replaceFile(temp, fileName);
        }
        File f = new File(temp);
        f.delete();
        return 0;
    }



    private void delInclude(String fileName, String temp) throws FileNotFoundException, IOException {
        FileHandler fh = new FileHandler();
        BufferedReader br = fh.openReadFile(fileName);
        BufferedWriter bw = fh.openWriteFile(temp);
        String tempStr = br.readLine();
        while(tempStr != null){
            if(!tempStr.contains("#INCLUDE")){
                bw.append(tempStr);
                bw.newLine();
            }
            tempStr = br.readLine();
        }
        fh.closeReadFile(br);
        fh.closeWriteFile(bw);
        System.gc();
        fh.replaceFile(temp, fileName);
    }

    private void include(String includeFileName, BufferedWriter bw) throws FileNotFoundException, IOException {
        FileHandler fh = new FileHandler();
        BufferedReader br = fh.openReadFile(includeFileName);
        
        String tempStr = br.readLine();
        while(tempStr != null){
            bw.append(tempStr);
            bw.newLine();
            tempStr = br.readLine();
        }
        fh.closeReadFile(br);

    }
}
